﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Sgr.Data;
using Sgr.EntityFrameworkCore.EntityConfigurations;
using Sgr.OmniMetrics.Domain;

namespace Sgr.OmniMetrics.Infrastructure.EntityConfigurations
{
    /// <summary>
    /// 指标实体配置
    /// </summary>
    internal class OmniMetricEntityConfiguration : EntityTypeConfigurationBase<OmniMetricEntity, long>
    {
        public OmniMetricEntityConfiguration(DatabaseType? databaseType = null) : base(databaseType)
        { }

        public override void Configure(EntityTypeBuilder<OmniMetricEntity> builder)
        {
            builder.ToTable("sgr_omnimetric");

            base.Configure(builder);

            builder.PropertyAndHasColumnName(b => b.MetricKey, GetColumnNameCase())
                .HasMaxLength(200)
                .IsRequired()
                .HasComment("指标唯一标识");

            builder.PropertyAndHasColumnName(b => b.TimeGranularity, GetColumnNameCase())
                .IsRequired()
                .HasComment("统计粒度");

            builder.PropertyAndHasColumnName(b => b.TimeValueUtc, GetColumnNameCase())
                .IsRequired()
                .HasComment("统计时间点");

            builder.PropertyAndHasColumnName(b => b.BasicValue01, GetColumnNameCase())
                .IsRequired()
                .HasComment("基础数值01");

            builder.PropertyAndHasColumnName(b => b.BasicValue02, GetColumnNameCase())
                .IsRequired()
                .HasComment("基础数值02");

            builder.PropertyAndHasColumnName(b => b.BasicValue03, GetColumnNameCase())
                .IsRequired()
                .HasComment("基础数值03");

            var prop = builder.PropertyAndHasColumnName(b => b.ExtendedValues, GetColumnNameCase())
                .HasComment("扩展数值（JSON序列化）");
            ConfigureJsonColumn(prop, Constant.ExtendableObjectMaxLength);

            builder.PropertyAndHasColumnName(b => b.UpdateTimeUtc, GetColumnNameCase())
                .IsRequired()
                .HasComment("指标值更新时间");

            // 设置索引
            // 设置复合索引，用于快速查询特定指标在特定粒度下的数据
            builder.HasIndex(e => new { e.MetricKey, e.TimeGranularity })
                .HasDatabaseName("IX_OmniMetric_Key_Granularity");

            // 设置唯一索引，确保同一指标在同一粒度下的同一时间点只有一条记录
            builder.HasIndex(e => new { e.MetricKey, e.TimeGranularity, e.TimeValueUtc })
                .IsUnique()
                .HasDatabaseName("UK_OmniMetric_Key_Granularity_TimeValue");
        }
    }
}